Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

226
Visualizações
Incrementing a "PlayerID" with a MongoDB Atlas Trigger

I need to have a playerID that is separate from _id and increments with each new entry into my users collection. I have tried to follow this tutorial with no luck. My counter collection is called playerIDCounter and my users collection is simply called users. I want each user document to have a playerID field that increments from 1 onwards.

This is my attempt at adapting the tutorial code for my own purpose:

exports = async function(changeEvent) {
const playerID = changeEvent.fullDocument.playerID;

const playerIDCounter = context.services.get("Cluster0").db(changeEvent.ns.db).collection("playerIDCounter");
const users = context.services.get("Cluster0").db(changeEvent.ns.db).collection(changeEvent.ns.coll);

(db.collection)
const counter = await playerIDCounter.findOneAndUpdate({playerID: changeEvent.ns },{$inc: { seq_value: 1 }}, { returnNewDocument: true, upsert : true});

const doc = {};

doc[`${changeEvent.ns.coll}.playerID`] = counter.seq_value;

const updateRes = await users.updateOne({playerID: playerID},{ $set: doc});

console.log(`Updated ${JSON.stringify(changeEvent.ns)} with counter ${counter.seq_value} result: ${JSON.stringify(updateRes)}`);

}

I also don't know whether or not I already need to have a playerID field in the document before it gets passed to this function. If the playerID field doesn't already exists will it be created and updated automatically? If not, then what placeholder value should playerID have?

I appreciate anyone who takes the time to help me. I have been stuck for a few days and there aren't too many posts on how to increment values in MongoDB.

Edit: I also don't understand the whole doc[`${changeEvent.ns.coll}.playerID`] = counter.seq_value bit - what's going on here?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda